package com.netease.nim.uikit.business.session.activity;

import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.TextView;
import android.widget.Toast;

import com.netease.nim.uikit.common.ToastHelper;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.netease.nim.uikit.R;
import com.netease.nim.uikit.api.NimUIKit;
import com.netease.nim.uikit.api.model.contact.ContactChangedObserver;
import com.netease.nim.uikit.api.model.main.OnlineStateChangeObserver;
import com.netease.nim.uikit.api.model.session.SessionCustomization;
import com.netease.nim.uikit.api.model.user.UserInfoObserver;
import com.netease.nim.uikit.api.wrapper.NimToolBarOptions;
import com.netease.nim.uikit.business.session.constant.Extras;
import com.netease.nim.uikit.business.session.fragment.MessageFragment;
import com.netease.nim.uikit.business.uinfo.UserInfoHelper;
import com.netease.nim.uikit.common.activity.ToolBarOptions;
import com.netease.nim.uikit.common.ui.imageview.HeadImageView;
import com.netease.nim.uikit.impl.NimUIKitImpl;
import com.netease.nimlib.sdk.NIMClient;
import com.netease.nimlib.sdk.Observer;
import com.netease.nimlib.sdk.RequestCallback;
import com.netease.nimlib.sdk.msg.MsgService;
import com.netease.nimlib.sdk.msg.MsgServiceObserve;
import com.netease.nimlib.sdk.msg.attachment.MsgAttachment;
import com.netease.nimlib.sdk.msg.constant.MsgStatusEnum;
import com.netease.nimlib.sdk.msg.constant.MsgTypeEnum;
import com.netease.nimlib.sdk.msg.constant.SessionTypeEnum;
import com.netease.nimlib.sdk.msg.model.CustomNotification;
import com.netease.nimlib.sdk.msg.model.IMMessage;
import com.netease.nimlib.sdk.msg.model.RecentContact;
import com.netease.nimlib.sdk.uinfo.UserService;
import com.netease.nimlib.sdk.uinfo.model.NimUserInfo;
import com.netease.nimlib.sdk.uinfo.model.UserInfo;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;

import me.goldze.mvvmhabit.binding.command.BindingConsumer;
import me.goldze.mvvmhabit.bus.Messenger;
import me.goldze.mvvmhabit.utils.KLog;


/**
 * 点对点聊天界面
 * <p/>
 * Created by huangjun on 2015/2/1.
 */
public class P2PMessageActivity extends BaseMessageActivity {

    private boolean isResume = false;

    public static void start(Context context, String contactId, SessionCustomization customization, IMMessage anchor) {
        Intent intent = new Intent();
        intent.putExtra(Extras.EXTRA_ACCOUNT, contactId);
        intent.putExtra(Extras.EXTRA_CUSTOMIZATION, customization);
        if (anchor != null) {
            intent.putExtra(Extras.EXTRA_ANCHOR, anchor);
        }
        intent.setClass(context, P2PMessageActivity.class);
        intent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP | Intent.FLAG_ACTIVITY_CLEAR_TOP);

        context.startActivity(intent);
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // 单聊特例话数据，包括个人信息，
        requestBuddyInfo();
        displayOnlineState();
        registerObservers(true);
        Messenger.getDefault().register(this, "shanchu",  String.class, new BindingConsumer<String>() {
            @Override
            public void call(String aMapLocation) {

                    finish();
            }
        });




    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        registerObservers(false);
        Messenger.getDefault().unregister(this, "shanchu");
    }

    @Override
    protected void onResume() {
        super.onResume();
        isResume = true;
    }

    @Override
    protected void onStop() {
        super.onStop();
        isResume = false;
    }

    private void requestBuddyInfo() {

        headImageView = findView(R.id.img_head);
        tvNickName = findView(R.id.tv_nickname);
        tv_goto = findView(R.id.tv_goto);
        ToolBarOptions options = new NimToolBarOptions();
        setToolBar(R.id.toolbar, options);


        NimUserInfo user = NIMClient.getService(UserService.class).getUserInfo(sessionId);
        if (sessionId == null){
            Toast.makeText(this,"传入空的用户ID",Toast.LENGTH_SHORT).show();
            finish();
        }
        NimUserInfo myUser = NIMClient.getService(UserService.class).getUserInfo(NimUIKit.getAccount());
        Log.d("HTML","user:"+user+" sessionId:"+sessionId);
//        ArrayList<String> list = new ArrayList<>();
//        list.add(se)
//        NIMClient.getService(UserService.class).fetchUserInfo(sessionId)
//                .setCallback(new RequestCallback<List<UserInfo>>() {
//                    @Override
//                    public void onSuccess(List<UserInfo> userInfos) {
//
//                    }
//
//                    @Override
//                    public void onFailed(int i) {
//
//                    }
//
//                    @Override
//                    public void onException(Throwable throwable) {
//
//                    } });

        if (user!=null &&  user.getExtensionMap()!=null)
        {
            headImageView.loadBuddyAvatar(sessionId);
            tvNickName.setText(user.getName());
            Log.d("HTML","user getAvatar :"+user.getAvatar()+" user.getName():"+user.getName());

            String Constellation  ="";

            if (user.getExtensionMap().get("Constellation") !=null){
                Constellation=  user.getExtensionMap().get("Constellation").toString();
            }
            try {
                double Latitude=  Double.valueOf(user.getExtensionMap().get("Latitude").toString());
                double Longitude= Double.valueOf( user.getExtensionMap().get("Longitude").toString());

                if (myUser!=null &&  myUser.getExtensionMap()!=null){
                    double aLatitude=  Double.valueOf(myUser.getExtensionMap().get("Latitude").toString());
                    double aLongitude=  Double.valueOf(myUser.getExtensionMap().get("Longitude").toString());

                    float ds = (float) (getDistance(Longitude,Latitude,aLongitude,aLatitude) /1000);
                    tv_goto.setText(ds+"km，"+Constellation);
                }
                else {
                    tv_goto.setText(Constellation);
                }
            }catch (Exception e){
                tv_goto.setText(Constellation);
            }

            
            // String age=  user.getExtensionMap().get("Age").toString();
            //   String xz = xz
            Log.d("HTML","user getExtensionMap :"+JSON.toJSONString( user.getExtensionMap()));

            // System.out.println(JSON.toJSONString( user.getExtensionMap()));
        }


        setTitle("");
    }

    private void displayOnlineState() {
        if (!NimUIKitImpl.enableOnlineState()) {
            return;
        }
        String detailContent = NimUIKitImpl.getOnlineStateContentProvider().getDetailDisplay(sessionId);
        setSubTitle(detailContent);
    }


    /**
     * 命令消息接收观察者
     */
    private Observer<CustomNotification> commandObserver = new Observer<CustomNotification>() {
        @Override
        public void onEvent(CustomNotification message) {
            if (!sessionId.equals(message.getSessionId()) || message.getSessionType() != SessionTypeEnum.P2P) {
                return;
            }
            showCommandMessage(message);
        }
    };


    /**
     * 用户信息变更观察者
     */
    private UserInfoObserver userInfoObserver = new UserInfoObserver() {
        @Override
        public void onUserInfoChanged(List<String> accounts) {
            if (!accounts.contains(sessionId)) {
                return;
            }
            requestBuddyInfo();
        }
    };

    /**
     * 好友资料变更（eg:关系）
     */
    private ContactChangedObserver friendDataChangedObserver = new ContactChangedObserver() {
        @Override
        public void onAddedOrUpdatedFriends(List<String> accounts) {
          // setTitle(UserInfoHelper.getUserTitleName(sessionId, SessionTypeEnum.P2P));
        }

        @Override
        public void onDeletedFriends(List<String> accounts) {
          // setTitle(UserInfoHelper.getUserTitleName(sessionId, SessionTypeEnum.P2P));
        }

        @Override
        public void onAddUserToBlackList(List<String> account) {
          //  setTitle(UserInfoHelper.getUserTitleName(sessionId, SessionTypeEnum.P2P));
        }

        @Override
        public void onRemoveUserFromBlackList(List<String> account) {
         //   setTitle(UserInfoHelper.getUserTitleName(sessionId, SessionTypeEnum.P2P));
        }
    };

    /**
     * 好友在线状态观察者
     */
    private OnlineStateChangeObserver onlineStateChangeObserver = new OnlineStateChangeObserver() {
        @Override
        public void onlineStateChange(Set<String> accounts) {
            if (!accounts.contains(sessionId)) {
                return;
            }
            // 按照交互来展示
            displayOnlineState();
        }
    };

    private void registerObservers(boolean register) {
        NIMClient.getService(MsgServiceObserve.class).observeCustomNotification(commandObserver, register);
        NimUIKit.getUserInfoObservable().registerObserver(userInfoObserver, register);
        NimUIKit.getContactChangedObservable().registerObserver(friendDataChangedObserver, register);
        if (NimUIKit.enableOnlineState()) {
            NimUIKit.getOnlineStateChangeObservable().registerOnlineStateChangeListeners(onlineStateChangeObserver, register);
        }
    }


    protected void showCommandMessage(CustomNotification message) {
        if (!isResume) {
            return;
        }
        String content = message.getContent();
        try {
            JSONObject json = JSON.parseObject(content);
            int id = json.getIntValue("id");
            if (id == 1) {
                // 正在输入
              //  ToastHelper.showToastLong(P2PMessageActivity.this, "对方正在输入...");
            } else {
              //  ToastHelper.showToast(P2PMessageActivity.this, "command: " + content);
            }
        } catch (Exception ignored) {

        }
    }

    @Override
    protected MessageFragment fragment() {
        Bundle arguments = getIntent().getExtras();
        arguments.putSerializable(Extras.EXTRA_TYPE, SessionTypeEnum.P2P);
        MessageFragment fragment = new MessageFragment();
        fragment.setArguments(arguments);
        fragment.setContainerId(R.id.message_fragment_container);
        return fragment;
    }
    HeadImageView headImageView;
    TextView tvNickName,tv_goto;
    @Override
    protected int getContentViewId() {
        return R.layout.nim_message_activity;
    }

    @Override
    protected void initToolBar() {

    }

    //调用菜单
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
     //   getMenuInflater().inflate(R.menu.nim_p2p_menu,menu); // 参数1为布局文件(menu_main.xml)

        getToolBar().inflateMenu(R.menu.nim_p2p_menu);
        return true;
    }


    @Override
    public boolean onOptionsItemSelected(MenuItem item) {

//        Bundle bds = new Bundle();
//        bds.putString("uid",sessionId);
//        ComponentName componetName = new ComponentName("com.jiamao.goplay","com.jiamao.goplay.base.LibContainerActivity");
//        Intent intent = new Intent();
//        intent.putExtra("fragment", "com.jiamao.goplay.ui.user.OthersUserInfoFragment");
//        intent.putExtra("bundle", bds);
//        intent.setComponent(componetName);
//        startActivity(intent);

        Messenger.getDefault().send(sessionId,"jiechu");

        return super.onOptionsItemSelected(item);
    }



    @Override
    protected boolean enableSensor() {
        return true;
    }

    private  final double EARTH_RADIUS = 6378137.0;
    public  double getDistance(double longitude,double latitue,double longitude2,double latitue2){
        double lat1 = rad(latitue);
        double lat2 = rad(latitue2);
        double a = lat1 - lat2;
        double b = rad(longitude)-rad(longitude2);
        double s = 2*Math.asin(Math.sqrt(Math.pow(Math.sin(a/2),2)+Math.cos(lat1)*Math.cos(lat2)*Math.pow(Math.sin(b/2),2)));
        s=s*EARTH_RADIUS;
        s=Math.round(s*10000)/10000;
        return s;
    }
    private  double rad(double d){
        return d*Math.PI/180.0;
    }


}
